package com.qf.security;

import cn.hutool.json.JSONUtil;
import com.github.pagehelper.util.StringUtil;
import com.qf.entity.SysUser;
import com.qf.entity.SysUserEntity;
import com.qf.utils.JwtUtils;
import com.qf.utils.RsaUtils;
import com.qf.vo.ResultVO;
import io.jsonwebtoken.JwtException;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.ResourceUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;

public class MyBasicAuthenticationFilter extends BasicAuthenticationFilter {
    public MyBasicAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String requestURI = request.getRequestURI();
        if ("/user/login".equals(requestURI)) {
            chain.doFilter(request, response);
            return;
        }if ("/user/check".equals(requestURI)) {
            chain.doFilter(request, response);
            return;
        }
        //从请求头中获取token
        String token = request.getHeader("token");

        if (StringUtil.isEmpty(token)) {
            response(response, new ResultVO(false, "令牌不能为空"));
        }

        try {
//            获取公钥
            PublicKey publicKey = RsaUtils.getPublicKey(ResourceUtils.getFile("classpath:rsa.pub").getPath());
//            解密token
            SysUser info = (SysUser) JwtUtils.getInfoFromToken(token, publicKey, SysUser.class);
//            获取用户的authorities
            String authority = info.getRoles() + "," + info.getPermissions();

//            利用工具类获取权限集
            List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(info, null, authorities);

//            将用户信息放到security的上下文路径中
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
//            放行
            chain.doFilter(request,response);
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof JwtException) {
                response(response, new ResultVO(false, "无效令牌!!!"));
            } else {
                response(response, new ResultVO(false, "其他异常！！！！"));
            }
        }
    }

    private void response(HttpServletResponse response, ResultVO res) {
        try {
            response.setContentType("application/json;charset=utf-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            PrintWriter writer = response.getWriter();
            writer.write(JSONUtil.toJsonStr(res));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
